import React, {
    Component,
} from 'react';
import LinearGradient from 'react-native-linear-gradient';
import {
    StyleSheet,
    Text,
    View,
    Platform,
    Dimensions,
    TouchableOpacity,
    Image,
    StatusBar,
    NativeModules,
    ScrollView,
    Switch, DeviceEventEmitter, ActivityIndicator,
    ToastAndroid,
    Clipboard,
    Alert,
    FlatList
} from 'react-native';
import ActionSheet from 'react-native-actionsheet'
import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Header from '../../components/header';
import { ToastToUser } from "../../utils/CustomToast";
import Constant from '../../utils/Constant'
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import AlertBox from "../../utils/AlertBox";
import ImageCropPicker from 'react-native-image-crop-picker';
import Upload from '../../components/upload/Upload'
import { requestCameraPermission,requestWritePermission } from '../../utils/Permission';

const isIos = Platform.OS == 'ios';
const screenW = Dimensions.get('window').width;
let navigation
let alertObj = {}

let selectClaimIndex = -1

export default class FoursQuerySubmit extends Component {
    constructor(props) {
        super(props);
        let propsData = this.props.route && this.props.route.params && this.props.route.params.data ? JSON.parse(this.props.route.params.data) : {}
        this.state = {
            data: propsData,
            price: '',
            vcode: '',
            brandLogo: '',
            brandName: '',
            brandId: '',
            driveLicenseImageUrl: '',
            weibaoList: [],
            claimList: [],
            availAmount: 0,

        }
    }



    componentWillUnmount() {

    }

    componentWillMount() {

    }

    componentDidMount() {
        this.formatData();
        this.requestavailAmount()
    }

    requestavailAmount() {
        HttpUtils.getRequest(HttpUrls.merchantAccountDetail, { merchantId: Constant.userInfo.merchantId })
            .then((result) => {
                let code = result.code
                if (code == 0) {
                    let data = result.data
                    this.setState({
                        availAmount: data.availAmount ? parseFloat(data.availAmount) : 0,
                    })
                }
            })
            .catch((error) => {

            });
    }

    formatData() {
        let driveLicenseImageUrl = this.state.driveLicenseImageUrl
        if (this.state.data) {
            this.setState({
                vcode: this.state.data.vin,
                brandLogo: this.state.data.brandLogo,
                brandName: this.state.data.brandName,
                brandId: this.state.data.brandId,
                weibaoList: this.state.data.weiBao,
                claimList: this.state.data.claim,
                driveLicenseImageUrl: driveLicenseImageUrl ? driveLicenseImageUrl : this.state.data.picUrl,
            }, function () {
                this.calculatePrice()
            })
        }
    }

    render() {
        navigation = this.props.navigation;
        return (
            <View style={styles.container}>
                <Header navigation={navigation} Title={'维保出险记录查询'} ></Header>

                <ScrollView showsVerticalScrollIndicator={false}>
                    <View style={styles.sepLine} />
                    <View style={styles.brandInfoBox}>
                        <View style={styles.brandBox}>
                            <Image style={styles.brandIcon} source={{ uri: this.state.brandLogo }} />
                            <Text style={styles.brandText}>{this.state.brandName}</Text>
                        </View>
                        <View style={styles.vinBox}>
                            <Text>{'VIN：' + this.state.vcode}</Text>
                        </View>
                    </View>
                    {
                        this.state.weibaoList && this.state.weibaoList.length > 0 ?
                            <View>
                                <View style={styles.sepLine} />
                                <View style={styles.weibaoBox}>
                                    <Text style={styles.weibaoTypeText}>请选择维保查询方式</Text>
                                    {
                                        this.state.weibaoList.map((item, index) => {
                                            return (
                                                <TouchableOpacity
                                                    activeOpacity={0.8}
                                                    style={item.check == 1 ? styles.itemSelBox : styles.itemBox}
                                                    onPress={this.changeWeibaoReport.bind(this, index)}>
                                                    <View style={styles.itemDesBox}>
                                                        <Text style={styles.itemTitleText}>{item.simpleMsg}</Text>
                                                        <Text style={styles.itemdesText}>{item.desMsg}</Text>
                                                    </View>
                                                    <View style={styles.itemPriceBox}>
                                                        <Text style={styles.itemPriceText}>{(item.price/100) + '元'}</Text>
                                                        {
                                                            item.originPrice ?
                                                            <Text style={styles.itemOriginPriceText}>{(item.originPrice/100) + '元'}</Text>
                                                            :
                                                            null
                                                        }
                                                    </View>
                                                </TouchableOpacity>
                                            )
                                        })
                                    }
                                </View>
                            </View>
                            :
                            null
                    }

                    {
                        this.state.claimList && this.state.claimList.length > 0 ?
                            <View>
                                <View style={styles.sepLine} />
                                <View style={styles.weibaoBox}>
                                    <Text style={styles.weibaoTypeText}>请选择出险查询方式</Text>
                                    {
                                        this.state.claimList.map((item, index) => {
                                            return (
                                                <TouchableOpacity
                                                    activeOpacity={0.8}
                                                    style={item.check == 1 ? styles.itemSelBox : styles.itemBox}
                                                    onPress={this.changeClaimReport.bind(this, index)}>
                                                    <View style={styles.itemDesBox}>
                                                        <Text style={styles.itemTitleText}>{item.simpleMsg}</Text>
                                                        <Text style={styles.itemdesText}>{item.desMsg}</Text>
                                                    </View>
                                                    <View style={styles.itemPriceBox}>
                                                        <Text style={styles.itemPriceText}>{(item.price/100) + '元'}</Text>
                                                        {
                                                            item.originPrice ?
                                                            <Text style={styles.itemOriginPriceText}>{(item.originPrice/100) + '元'}</Text>
                                                            :
                                                            null
                                                        }
                                                    </View>
                                                </TouchableOpacity>
                                            )
                                        })
                                    }
                                </View>
                            </View>
                            :
                            null
                    }

                    <View style={styles.sepLine} />
                    <View style={styles.payTypeBox}>
                        <View style={styles.payTypeTitleBox}>
                            <Text style={styles.weibaoTypeText}>支付方式</Text>
                        </View>
                        <View style={[styles.payTypeTitleBox, { borderBottomWidth: 0 }]}>
                            <Image style={styles.payTypeIcon} source={require('source/image/pay/cash_pay.png')} />
                            <Text style={[styles.itemTitleText, { marginLeft: 10 }]}>余额支付</Text>
                            <Text style={styles.moneyText}>{'总余额：' + (this.state.availAmount / 100).toFixed(2) + '元'}</Text>
                        </View>
                    </View>

                </ScrollView>

                {/*支付信息*/}
                <View style={[styles.bottomBox, { height: 50 + Constant.bottomHeight }]}>
                    <View style={styles.bottomBox1}>
                        <Text style={styles.totalPriceText}>{'总价：' + (this.state.price/100) + '元'}</Text>
                        <TouchableOpacity
                            activeOpacity={0.6}
                            style={styles.payBox}
                            onPress={() => {
                                this.pay()
                            }}
                        >
                            <Text style={styles.payText}>支付查询</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                <Loading onRef={(ref) => (this.Loading = ref)} />

                <ActionSheet
                    ref={o => this.ActionSheet = o}
                    title={'请选择照片来源 ?'}
                    options={['相册', '拍照', '取消']}
                    cancelButtonIndex={2}
                    onPress={(index) => { this.selectPhoto(index) }}
                />

                <AlertBox
                    onRef={(ref) => (this.AlertBox = ref)}
                    sureHandler={() => {
                        if (alertObj.uploadDriveLicense) {
                            this.uploadDriveLicense()
                        } else {
                            navigation.replace('FoursQueryHistory')
                        }
                    }}
                    cancelHandler={() => {
                        if (!alertObj.uploadDriveLicense) {
                            navigation.goBack()
                        }
                    }}
                />

            </View>
        )
    }

    //选择相册还是照相机
    selectPhoto(index) {
        if (index == 0) {
            //相册
            const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, multiple: false };
            ImageCropPicker.openPicker(option).then(images => {
                if (this.Loading) {
                    this.Loading.show();
                }
                Upload.getAlipz(images.path, Upload.ossTypeImage, this.uploadafterfun);//获取阿里凭证。

            }, (error) => {
                // alert(error);
            });

        } else if (index == 1) {
            //照相机
            this.openCamera();
        }
    }

    openCamera() {
        if (isIos) {
            this.takePhoto()
        }else{
            requestCameraPermission().then((result) => {
                if (result) {
                   this.takePhoto()
                }else{
                    ToastToUser('权限获取失败')
                }
            })
        }
    }

    takePhoto(){
        const option = { mediaType: "photo", cropping: false, compressImageQuality: .8, compressImageMaxWidth: 1024, compressImageMaxHeight: 1024 };
        ImageCropPicker.openCamera(option).then(images => {
            if (this.Loading) {
                this.Loading.show() 
            }
            Upload.getAlipz(images.path, Upload.ossTypeImage, this.uploadafterfun);//获取阿里凭证。

        }, (error) => {
            // alert(error);
        });
    }

     // 上传图片成功后 回调
     uploadafterfun = (picUrl) => {
        if (this.Loading) {
            this.Loading.hide();
        }
        this.setState({
            driveLicenseImageUrl: picUrl
        }, function () {
            if (selectClaimIndex >= 0) {
                this.changeClaimReport(selectClaimIndex)
            }
        })
     }

    changeWeibaoReport(index) {
        let temp = []
        let hasSelectClaim = false;
        this.state.claimList.map((item, index) => {
            if (item.check == 1) {
                hasSelectClaim = true
            }
        })

        if (hasSelectClaim) {//已选中碰撞查询
            this.state.weibaoList.map((item, currIndex) => {
                if (currIndex == index) {
                    if (item.check == 1) {
                        item.check = 0
                    } else {
                        item.check = 1
                    }
                } else {
                    item.check = 0
                }
                temp.push(item);
            })
        } else {//没有选中碰撞查询
            this.state.weibaoList.map((item, currIndex) => {
                if (currIndex == index) {
                    if (item.check == 1) {
                        ToastToUser('至少选择维保或者出险查询的一种')
                    } else {
                        item.check = 1
                    }
                } else {
                    item.check = 0
                }
                temp.push(item);
            })
        }

        this.setState({
            weibaoList: temp
        }, function () {
            this.calculatePrice()
        })

    }

    changeClaimReport(index) {
        selectClaimIndex = index

        let temp = []
        let hasSelectWeibao = false;
        this.state.weibaoList.map((item, index) => {
            if (item.check == 1) {
                hasSelectWeibao = true
            }
        })

        let selectItem = this.state.claimList[index]
        if (hasSelectWeibao) {//已选中维保查询
            if (selectItem.needLicenseUrl == 'true' && !this.state.driveLicenseImageUrl) {
                temp = this.state.claimList;
            } else {
                this.state.claimList.map((item, currIndex) => {
                    if (currIndex == index) {
                        if (item.check == 1) {
                            item.check = 0
                        } else {
                            item.check = 1
                        }
                    } else {
                        item.check = 0
                    }
                    temp.push(item);
                })
            }

        } else {//没有选中维保查询
            if (selectItem.needLicenseUrl == 'true' && !this.state.driveLicenseImageUrl) {
                temp = this.state.claimList;
            } else {
                this.state.claimList.map((item, currIndex) => {
                    if (currIndex == index) {
                        if (item.check == 1) {
                            ToastToUser('至少选择维保或者碰撞查询的一种')
                        } else {
                            item.check = 1
                        }
                    } else {
                        item.check = 0
                    }
                    temp.push(item);
                })
            }
        }

        if (temp != this.state.claimList) {
            this.setState({
                claimList: temp
            }, function () {
                this.calculatePrice()
            })
        } else {
            alertObj = {
                desc: '上传完整清晰的行驶证图片查询碰撞详版，查成功率99%，是否上传行驶证图片',
                cancelTitle: '取消',
                sureTitle: '上传行驶证',
                uploadDriveLicense: true
            }
            this.AlertBox.show(alertObj)
        }
    }

    calculatePrice() {
        let totalPrice = 0
        this.state.weibaoList.map((item) => {
            if (item.check == 1) {
                totalPrice = totalPrice + item.price
            }
        })
        this.state.claimList.map((item) => {
            if (item.check == 1) {
                totalPrice = totalPrice + item.price
            }
        })
        this.setState({
            price: totalPrice
        })
    }

    uploadDriveLicense() {
        this.ActionSheet.show()
    }

    pay() {
        if (this.state.availAmount < this.state.price) {
            ToastToUser('余额不足，请先充值!')
            return
        }

        let params = {
            vin: this.state.vcode,
            brandLogo: this.state.brandLogo,
            brandId: this.state.brandId,
            brandName: this.state.brandName,
            operator: Constant.userInfo.fullname,
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId
        }

        if (this.state.driveLicenseImageUrl) {
            params['picUrl'] = this.state.driveLicenseImageUrl
        }

        this.state.weibaoList.map((item) => {
            if (item.check == 1) {
                params['weibaoType'] = item.type,
                    params['weibaoDesMsg'] = item.simpleMsg
            }
        })

        this.state.claimList.map((item) => {
            if (item.check == 1) {
                params['claimType'] = item.type,
                    params['claimDesMsg'] = item.simpleMsg
            }
        })


        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.postRequest(HttpUrls.weibaoCommit, params)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result && result.success == true) {
                    this.weibaoPay(result.data)
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                ToastToUser('提交失败')
            });
    }

    weibaoPay(orderNo) {

        let totalAmount = 0
        this.state.weibaoList.map((item) => {
            if (item.check == 1) {
                totalAmount = totalAmount + item.price
            }
        })

        this.state.claimList.map((item) => {
            if (item.check == 1) {
                totalAmount = totalAmount + item.price
            }
        })

        let param = {
            userId: Constant.userInfo.userId,
            merchantId: Constant.userInfo.merchantId,
            merchantName: Constant.userInfo.merchantName,
            userFullName: Constant.userInfo.fullname,
            totalAmount: totalAmount,
            payChannel: 3,
            bizOrderId: 0,
            outTradeNo: orderNo,
            tradeType: 1
        }
        if (this.Loading) {
            this.Loading.show();
        }
        HttpUtils.postRequest(HttpUrls.paymentOrderGenerate, param)
            .then((result) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                if (result && result.success == true) {
                    alertObj = {
                        desc: '查询请求已提交，稍后请在查询记录中，查看本次查询结果',
                        cancelTitle: '返回',
                        sureTitle: '查看记录'
                    }
                    this.AlertBox.show(alertObj)
                } else {
                    ToastToUser(result.msg)
                }
            })
            .catch((error) => {
                if (this.Loading) {
                    this.Loading.hide();
                }
                ToastToUser('提交失败')
            });
    }

}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#F9F9F9',
    },
    sepLine: {
        width: '100%',
        height: 10
    },

    brandInfoBox: {
        width: '100%',
        flexDirection: 'column',
        paddingHorizontal: 10,
        backgroundColor: '#ffffff'
    },
    brandBox: {
        width: '100%',
        height: 74,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5
    },
    brandIcon: {
        width: 50,
        height: 50,
    },
    brandText: {
        marginLeft: 10,
        color: '#222222',
        fontSize: 15,
        fontWeight: '500'
    },
    vinBox: {
        width: '100%',
        flexDirection: 'row',
        height: 45,
        alignItems: 'center'
    },
    weibaoBox: {
        backgroundColor: '#ffffff',
        paddingVertical: 12,
        paddingHorizontal: 10
    },
    weibaoTypeText: {
        height: 22,
        color: '#222222',
        fontSize: 16,
        fontWeight: '500',
    },
    itemSelBox: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        marginTop: 12,
        width: '100%',
        height: 60,
        borderRadius: 4,
        borderWidth: 1,
        borderColor: '#FCDD12'
    },
    itemBox: {
        backgroundColor: '#F9F9F9',
        flexDirection: 'row',
        alignItems: 'center',
        paddingHorizontal: 10,
        marginTop: 12,
        width: '100%',
        height: 60,
        borderRadius: 4,
    },
    itemDesBox: {
        flexDirection: 'column',
        justifyContent: 'center',
        height: '100%',
        flex: 1,
        marginRight: 15
    },
    itemPriceBox: {
        flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'flex-end',
        height: '100%',
    },
    itemTitleText: {
        color: '#222222',
        fontSize: 14,
    },
    itemdesText: {
        marginTop: 5,
        color: '#999999',
        fontSize: 12
    },
    itemPriceText: {
        color: '#F99802',
        fontSize: 18,
        fontWeight: 'bold'
    },
    itemOriginPriceText: {
        marginTop: 5,
        color: '#999999',
        fontSize: 12,
        textDecorationLine: 'line-through'
    },
    itemSelIcon: {
        position: 'absolute',
        right: 12,
        width: 20,
        height: 20
    },

    payTypeBox: {
        backgroundColor: '#ffffff',
        paddingHorizontal: 10,
    },
    payTypeTitleBox: {
        height: 50,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomColor: '#E4E4E4',
        borderBottomWidth: 0.5,
    },
    payTypeIcon: {
        width: 24,
        height: 24
    },
    moneyText: {
        position: 'absolute',
        right: 10,
        fontSize: 14,
        color: '#CCCCCC'
    },

    bottomBox: {
        backgroundColor: '#fff',
        width: '100%',
    },
    bottomBox1: {
        backgroundColor: '#fff',
        width: '100%',
        height: 50,
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
    },
    totalPriceText: {
        marginLeft: 11,
        color: '#222222',
        fontSize: 14
    },
    payBox: {
        backgroundColor: '#FCDD12',
        width: 100,
        height: 50,
        justifyContent: 'center',
        alignItems: 'center'
    },
    payText: {
        color: '#222222',
        fontSize: 15,
        fontWeight: '500'
    }
})